package capsolver_go

import (
	"errors"
	"fmt"
	"gitee.com/kaylee595/gkaylee/kerr"
	"github.com/imroc/req/v3"
	"net/http"
)

type ErrApiCode string

const (
	ErrApiCodeServiceUnavaliable ErrApiCode = "ERROR_SERVICE_UNAVALIABLE"
	ErrApiCodeRateLimit          ErrApiCode = "ERROR_RATE_LIMIT"
	ErrApiCodeInvalidTaskData    ErrApiCode = "ERROR_INVALID_TASK_DATA"
	ErrApiCodeBadRequest         ErrApiCode = "ERROR_BAD_REQUEST"
	ErrApiCodeTaskIdInvalid      ErrApiCode = "ERROR_TASKID_INVALID"
	ErrApiCodeTaskTimeout        ErrApiCode = "ERROR_TASK_TIMEOUT"
	ErrApiCodeSettlementFailed   ErrApiCode = "ERROR_SETTLEMENT_FAILED"
	ErrApiCodeKeyDeniedAccess    ErrApiCode = "ERROR_KEY_DENIED_ACCESS"
	ErrApiCodeZeroBalance        ErrApiCode = "ERROR_ZERO_BALANCE"
	ErrApiCodeTaskNotSupported   ErrApiCode = "ERROR_TASK_NOT_SUPPORTED"
	ErrApiCodeCaptchaUnsolvable  ErrApiCode = "ERROR_CAPTCHA_UNSOLVABLE"
	ErrApiCodeUnknownQuestion    ErrApiCode = "ERROR_UNKNOWN_QUESTION"
	ErrApiCodeProxyBanned        ErrApiCode = "ERROR_PROXY_BANNED"
	ErrApiCodeInvalidImage       ErrApiCode = "ERROR_INVALID_IMAGE"
	ErrApiCodeParseImageFail     ErrApiCode = "ERROR_PARSE_IMAGE_FAIL"
	ErrApiCodeIpBanned           ErrApiCode = "ERROR_IP_BANNED"
	ErrApiCodeKeyTempBlocked     ErrApiCode = "ERROR_KEY_TEMP_BLOCKED"
	ErrApiCodeCaptchaSolveFailed ErrApiCode = "ERROR_CAPTCHA_SOLVE_FAILED"

	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = ErrApiCodeServiceUnavaliable, ErrApiCodeRateLimit, ErrApiCodeInvalidTaskData, ErrApiCodeBadRequest,
		ErrApiCodeTaskIdInvalid, ErrApiCodeTaskTimeout, ErrApiCodeSettlementFailed, ErrApiCodeKeyDeniedAccess, ErrApiCodeZeroBalance,
		ErrApiCodeTaskNotSupported, ErrApiCodeCaptchaUnsolvable, ErrApiCodeUnknownQuestion, ErrApiCodeProxyBanned, ErrApiCodeInvalidImage,
		ErrApiCodeParseImageFail, ErrApiCodeIpBanned, ErrApiCodeKeyTempBlocked, ErrApiCodeCaptchaSolveFailed
)

type ErrApi struct {
	ErrorId          int        `json:"errorId"`
	ErrorCode        ErrApiCode `json:"errorCode"`
	ErrorDescription string     `json:"errorDescription"`
}

func (e *ErrApi) IsError() bool {
	return e.ErrorId != 0
}

func (e *ErrApi) Error() string {
	return fmt.Sprintf("id: %d, code: %s, description: %s", e.ErrorId, e.ErrorCode, e.ErrorDescription)
}

var ErrUnauthorized = errors.New("authentication failed, indicating that the API key is not correct")

func checkError(_ *req.Client, resp *req.Response) error {
	if resp.Err != nil {
		return resp.Err
	}
	if resp.StatusCode == http.StatusUnauthorized {
		return kerr.WrapTraceStack(ErrUnauthorized)
	}
	apiErr := new(ErrApi)
	if err := resp.UnmarshalJson(apiErr); err != nil {
		return kerr.WrapTraceStack(err)
	}
	if apiErr.IsError() {
		return kerr.WrapTraceStack(apiErr)
	}
	return nil
}
